package org.study.redis.boot.job;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.idev.excel.EasyExcel;
import cn.idev.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年07月01日
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GfjkDataJob {
    String DESKTOP = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
    private final RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/10 9-18 * * ?")// 每天9点到18点时间范围内每十分钟执行一次
    public void exportData() throws IOException {
        LocalDateTime localDateTime = LocalDateTime.now();
        String date = LocalDateTimeUtil.format(localDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String datetime = LocalDateTimeUtil.format(localDateTime, DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        File saveDir = new File(DESKTOP + File.separator + date);
        FileUtil.mkdir(saveDir);

        Map<String, BigDecimal> s1001CacheData = redisTemplate.opsForHash().entries("broker:gfjk:em00240203f100:S1001:lastCache");
        log.info("s1001CacheData={}", JSON.toJSONString(s1001CacheData));
        List<DeviceExportBO> s1001Data = Lists.newArrayList();
        String s1001_xlsx = new ClassPathResource("excel/S1001.xlsx").getFile().getPath();
        List<DeviceImportBO> s1001ImportBOList = EasyExcel.read(s1001_xlsx)
                .head(DeviceImportBO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doReadSync();
        s1001ImportBOList.forEach(s1001ImportBO -> {
            DeviceExportBO deviceExportBO = new DeviceExportBO();
            BeanUtils.copyProperties(s1001ImportBO, deviceExportBO);
            Object data = s1001CacheData.get(s1001ImportBO.getId());
            if (data instanceof Double) {
                deviceExportBO.setValue(new BigDecimal(data.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            } else if (data != null) {
                deviceExportBO.setValue(data.toString());
            } else {
                deviceExportBO.setValue("0");
            }
            s1001Data.add(deviceExportBO);
        });
        EasyExcel.write(saveDir.getPath() + File.separator + "S1001_data_export_" + datetime + ".xlsx", DeviceExportBO.class)
                .sheet("S1001设备数据")
                .doWrite(s1001Data);


        Map<String, BigDecimal> s1002CacheData = redisTemplate.opsForHash().entries("broker:gfjk:em00240203f100:S1002:lastCache");
        log.info("s1002CacheData={}", JSON.toJSONString(s1002CacheData));
        List<DeviceExportBO> s1002Data = Lists.newArrayList();
        String s1002_xlsx = ResourceUtils.getFile("classpath:excel/S1002.xlsx").getPath();
        List<DeviceImportBO> s1002ImportBOList = EasyExcel.read(s1002_xlsx)
                .head(DeviceImportBO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doReadSync();
        s1002ImportBOList.forEach(s1002ImportBO -> {
            DeviceExportBO deviceExportBO = new DeviceExportBO();
            BeanUtils.copyProperties(s1002ImportBO, deviceExportBO);
            Object data = s1002CacheData.get(s1002ImportBO.getId());
            if (data instanceof Double) {
                deviceExportBO.setValue(new BigDecimal(data.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            } else if (data != null) {
                deviceExportBO.setValue(data.toString());
            } else {
                deviceExportBO.setValue("0");
            }
            s1002Data.add(deviceExportBO);
        });
        EasyExcel.write(saveDir.getPath() + File.separator + "S1002_data_export_" + datetime + ".xlsx", DeviceExportBO.class)
                .sheet("S1002设备数据")
                .doWrite(s1002Data);


        Map<String, BigDecimal> s1003CacheData = redisTemplate.opsForHash().entries("broker:gfjk:em00240203f100:S1003:lastCache");
        log.info("s1003CacheData={}", JSON.toJSONString(s1003CacheData));
        List<DeviceExportBO> s1003Data = Lists.newArrayList();
        String s1003_xlsx = ResourceUtils.getFile("classpath:excel/S1003.xlsx").getPath();
        List<DeviceImportBO> s1003ImportBOList = EasyExcel.read(s1003_xlsx)
                .head(DeviceImportBO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doReadSync();
        s1003ImportBOList.forEach(s1003ImportBO -> {
            DeviceExportBO deviceExportBO = new DeviceExportBO();
            BeanUtils.copyProperties(s1003ImportBO, deviceExportBO);
            Object data = s1003CacheData.get(s1003ImportBO.getId());
            if (data instanceof Double) {
                deviceExportBO.setValue(new BigDecimal(data.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            } else if (data != null) {
                deviceExportBO.setValue(data.toString());
            } else {
                deviceExportBO.setValue("0");
            }
            s1003Data.add(deviceExportBO);
        });
        EasyExcel.write(saveDir.getPath() + File.separator + "S1003_data_export_" + datetime + ".xlsx", DeviceExportBO.class)
                .sheet("S1003设备数据")
                .doWrite(s1003Data);

        log.info("定时导出设备最新点位数据成功");
    }
}
